# encoding: utf-8

from annoying.decorators import render_to
from django.shortcuts import redirect
from core.forms import LoginForm
from core.models import InternalCredential
from hashlib import md5
from core.views import index
from django.forms import forms


@render_to('login.html')
def login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            login = form.cleaned_data['login']
            password = form.cleaned_data['password']
            internal_credential = InternalCredential(login=login,
                password_hash=md5(password).hexdigest())
            user = internal_credential.authenticate()
            if user is None:
                form.errors[forms.NON_FIELD_ERRORS] = ['Incorrect login or password.']
                return {'form': form}
            request.session['user_id'] = user.id
            return_to = request.GET.get('return_to')
            return redirect(return_to or index)
    else:
        form = LoginForm()
    return {'form': form}
